package cn.lay.service.Impl;

import cn.lay.mapper.goodsMapper;
import cn.lay.pojo.linkman;
import cn.lay.service.goodsService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class goodsServiceImpl implements goodsService {

    @Resource
    private goodsMapper goodsMapper;

    @Override
    public JSONObject findAll(int page, int limit) {
        JSONObject result = new JSONObject();
        //接收数据
        try {
            PageHelper.startPage(page, limit);
            PageInfo<linkman> pageInfo = new PageInfo(goodsMapper.findAll());
            result.put("code", "0"); //设置状态码
            result.put("msg", "操作成功"); //设置信息
            result.put("data", pageInfo.getList()); //获取数据集合
            result.put("count", pageInfo.getTotal()); //获取分页总数
        } catch (Exception e) {
            result.put("code", "500");
            result.put("msg", "查询异常！");
        }
        return result;
    }

    @Override
    public JSONObject deleteById(Integer id) {
        /*使用JSON*/
        JSONObject result = new JSONObject();
        try {
            goodsMapper.deleteById(id);
            result.put("code", 0);
            result.put("msg", "删除成功,编号为" + id);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "异常,删除失败！");
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public JSONObject updateById(linkman linkman) {
        JSONObject result = new JSONObject();
        try {
            goodsMapper.updateById(linkman);
            result.put("code", 0);
            result.put("msg", "修改,编号为" + linkman.getId());
        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "异常,修改失败！");
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public JSONObject add(linkman linkman) {
        JSONObject result = new JSONObject();
        try {
            goodsMapper.add(linkman);
            result.put("code", 0);
            result.put("msg", "添加成功");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "异常,添加失败！");
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public JSONObject findTplPage() {
        JSONObject result = new JSONObject();
        //接收数据
        try {
            List<linkman> list = goodsMapper.findAll();
            result.put("code", "0"); //设置状态码
            result.put("msg", "操作成功"); //设置信息
            result.put("data", JSON.toJSON(list)); //获取数据集合

        } catch (Exception e) {
            result.put("code", "500");
            result.put("msg", "查询异常！");
        }
        return result;
    }
}
